
import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_pack_up_keyboard_widget/common_pack_up_keyboard_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_search_bar_widget/common_search_bar_widget.dart';
import 'package:e_reception_flutter/media_library/media_library_index/pages/media_play_time_page.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/new_terminal/new_terminal_list/bean/new_terminal_response_bean.dart';
import 'package:e_reception_flutter/ui/new_terminal/new_terminal_list/bean/terminal_by_pic_response_bean.dart';
import 'package:e_reception_flutter/ui/new_terminal/new_terminal_list/event/terminal_list_refresh_event.dart';
import 'package:e_reception_flutter/ui/new_terminal/new_terminal_list/new_terminal_list_view_model.dart';
import 'package:e_reception_flutter/ui/new_terminal/terminal_detail/terminal_detail_view_model.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/utils/vg_role_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_base/vg_time_util_lib.dart';

///添加播放终端页面
class MediaAddTerminalByPicPage extends StatefulWidget{
  ///路由名称
  static const String ROUTER = "MediaAddTerminalByPicPage";
  ///是否是添加已有照片到终端
  final bool addTerminal;
  final String startday;
  final String endday;
  final String picid;
  final String hsns;
  ///对于不是超管的普通管理员，针对不能管理的终端，拼着hsns一起传过去
  final String cantManageHsns;
  ///没有选择终端时，此时去添加终端，完成后需要跳转到设置时间页面
  final bool setTimeFlag;



  const MediaAddTerminalByPicPage({Key key,this.addTerminal, this.setTimeFlag,
    this.startday, this.endday, this.picid, this.hsns, this.cantManageHsns}):super(key: key);

  @override
  _MediaAddTerminalByPicPageState createState() => _MediaAddTerminalByPicPageState();

  ///跳转方法
  static Future<String> navigatorPush(
      BuildContext context, {bool addTerminal, bool setTimeFlag, String startday,
        String endday, String picid, String hsns, String cantManageHsns}) {
    return RouterUtils.routeForFutureResult(
      context, MediaAddTerminalByPicPage(
      addTerminal: addTerminal,
      setTimeFlag: setTimeFlag,
      startday: startday,
      endday: endday,
      picid: picid,
      hsns: hsns,
      cantManageHsns: cantManageHsns,
    ),
      routeName: MediaAddTerminalByPicPage.ROUTER,
    );
  }
}

class _MediaAddTerminalByPicPageState extends BaseState<MediaAddTerminalByPicPage>{
  NewTerminalListViewModel _viewModel;
  String _searchStr;
  bool _selectAll = false;
  String _hsns = "";
  @override
  void initState() {
    super.initState();
    _viewModel = NewTerminalListViewModel(this, searchStrFunc: () => _searchStr);
    _viewModel.getTerminalListByPicWithoutHsn(context, widget?.picid,terminalname: _searchStr);
    VgEventBus.global.on().listen((event) {
      if(event is TerminalListRefreshEvent){
        _viewModel.refresh();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomPadding: false,
      resizeToAvoidBottomInset: false,
      backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      body: CommonPackUpKeyboardWidget(
        child: Column(
          children: [
            _toTopBarWidget(),
            Expanded(child: _toPlaceHolderWidget()),
          ],
        ),
      ),
    );
  }

  ///标题栏
  Widget _toTopBarWidget(){
    return VgTopBarWidget(
      isShowBack: true,
      title: "请选择",
      backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
    );
  }

  ///搜索
  Widget _toSearchWidget(){
    return Container(
      color: ThemeRepository.getInstance().getCardBgColor_21263C(),
      child: Column(
        children: <Widget>[
          SizedBox(height: 10),
          CommonSearchBarWidget(
            hintText: "搜索名字",
            // onChanged: (String searchStr) => _searchStr = searchStr,
            onSubmitted: (String searchStr) {
              _searchStr = searchStr;
              _viewModel.getTerminalListByPicWithoutHsn(context, widget?.picid,terminalname: _searchStr);
            },
          ),
          SizedBox(height: 10),
        ],
      ),
    );
  }

  Widget _toPlaceHolderWidget(){
    return ValueListenableBuilder(
        valueListenable: _viewModel?.statusTypeValueNotifier,
        builder:
            (BuildContext context, PlaceHolderStatusType value, Widget child) {
          return VgPlaceHolderStatusWidget(
            loadingStatus: value == PlaceHolderStatusType.loading,
            errorStatus: value == PlaceHolderStatusType.error,
            emptyStatus: value == PlaceHolderStatusType.empty,
            errorOnClick: () => _viewModel
                .getTerminalListByPicWithoutHsn(context, widget?.picid),
            loadingOnClick: () => _viewModel
                .getTerminalListByPicWithoutHsn(context, widget?.picid),
            child: child,
          );
        },
        child: _toBodyWidget());
  }


  Widget _toBodyWidget(){
    return ValueListenableBuilder(
        valueListenable: _viewModel?.terminalByPicWithoutHsnValueNotifier,
        builder: (BuildContext context, List<NewTerminalListItemBean> data, Widget child){
          if(data != null){
              int count = 0;
                data.forEach((element) {
                  if(element.selectStatus){
                    count++;
                  }
                });
              if(count == data?.length??0){
                _selectAll = true;
              }
          }

          return CommonPackUpKeyboardWidget(
            child: Column(
              children: <Widget>[
                _toSearchWidget(),
                Expanded(
                    child: _toListWidget(data)),
                _toConfirmWidget(data),
              ],
            ),
          );
        }
    );
  }

  ///图片展示栏
  Widget _toListWidget(List<NewTerminalListItemBean> data){

    return ListView.separated(
      padding: EdgeInsets.only(top: 0),
      shrinkWrap: true,
      itemBuilder: (BuildContext context, int index) {
        return _toListItemWidget(context, index, data?.elementAt(index), data);
      },
      separatorBuilder: (BuildContext context, int index){
        return SizedBox();
      },
      itemCount: data?.length??0,
    );

  }

  ///item
  Widget _toListItemWidget(BuildContext context, int index, NewTerminalListItemBean itemBean,
      List<NewTerminalListItemBean> data){
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: ()  {
        setState(() {
          itemBean.selectStatus = !itemBean.selectStatus??false;
          _selectAll = _getSelectedCount(data) == data?.length;
        });
      },
      child: Container(
        height: 79,
        child: Row(
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 15),
              child: Image.asset(
                (itemBean.selectStatus??false
                    ? "images/common_selected_ico.png"
                    : "images/common_unselect_ico.png"),
                height: 20,
              ),
            ),

            Expanded(child: _toContentWidget(index, itemBean)),
          ],
        ),
      ),
    );
  }

  Widget _toContentWidget(int index, NewTerminalListItemBean itemBean) {

    return Container(
      margin: const EdgeInsets.only(right: 12),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Row(
            children: [
              Visibility(
                visible: (StringUtils.isEmpty(itemBean?.terminalName) && StringUtils.isEmpty(itemBean?.sideNumber)&& StringUtils.isNotEmpty(itemBean?.hsn)),
                child: Text(
                  // "硬件ID：",
                  "",
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 15,
                    // fontWeight: FontWeight.w600
                  ),
                ),
              ),
              Expanded(
                child: Text(
                  itemBean?.getTerminalName(index),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 15,
                    // fontWeight: FontWeight.w600
                  ),
                ),
              ),
              Spacer(),
              Visibility(
                child: Container(
                  alignment: Alignment.centerRight,
                  width: 60,
                  child: Text(
                  itemBean.getTerminalStateString(),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(
                      color: (itemBean?.getTerminalIsOff()??true)
                          ?ThemeRepository.getInstance().getDefaultGrayColor_FF5E687C()
                          :ThemeRepository.getInstance().getHintGreenColor_00C6C4(),
                      fontSize: 12,
                    ),
                  ),
                ),
              ),
            ],
          ),
          Container(
            width: 236,
            child: Text(
              showOriginEmptyStr(itemBean?.position) ?? itemBean?.address ?? "",
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(
                color: VgColors.INPUT_BG_COLOR,
                fontSize: 12,
              ),
            ),
          ),
          Text(
            "管理员：${itemBean?.manager ?? "-"}${_getLoginStr(itemBean?.loginName) ?? ""}",
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
              color: VgColors.INPUT_BG_COLOR,
              fontSize: 12,
            ),
          )
        ],
      ),
    );
  }

  String _getLoginStr(String loginName) {
    if (loginName == null || loginName == "") {
      return null;
    }
    return "（$loginName账号登录）";
  }

  int _getSelectedCount(List<NewTerminalListItemBean> data){
    int count = 0;
    if(data != null){
      data.forEach((element) {
        if((element.selectStatus??false)){
          count++;
        }
      });
    }
    return count;
  }

  ///确定
  Widget _toConfirmWidget(List<NewTerminalListItemBean> data){
    if(data == null || data.length < 1){
      return Container();
    }
    return Container(
      height: 56,
      color: ThemeRepository.getInstance().getLineColor_3A3F50(),
      child: Row(
        children: <Widget>[
          GestureDetector(
            onTap: (){
              setState(() {
                data.forEach((element) {
                  element.selectStatus = !_selectAll;
                });
                _selectAll = !_selectAll;
              });
            },
            child: Padding(
              padding: const EdgeInsets.symmetric(horizontal: 15),
              child: Text(
                _selectAll?"全不选":"全选",
                style: TextStyle(
                  fontSize: 15,
                  color: ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
                ),
              ),
            ),
          ),
          Visibility(
            visible: _getSelectedCount(data) > 0,
            child: Text(
              "已选${_getSelectedCount(data)}终端",
              style: TextStyle(
                fontSize: 12,
                color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
              ),
            ),
          ),
          Spacer(),
          CommonFixedHeightConfirmButtonWidget(
            isAlive: true,
            height: 36,
            width: 90,
            margin: const EdgeInsets.symmetric(horizontal: 15),
            unSelectBgColor: Color(0xFF3A3F50),
            selectedBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
            unSelectTextStyle: TextStyle(
              color: VgColors.INPUT_BG_COLOR,
              fontSize: 15,
            ),
            selectedTextStyle: TextStyle(
              color: Colors.white,
              fontSize: 15,
              // fontWeight: FontWeight.w600
            ),
            text: "确定",
            onTap: (){
                if(widget?.setTimeFlag??false){
                  DateTime startDay = DateTime.parse(DateUtil.getDateStrByDateTime(DateTime.now(), format: DateFormat.YEAR_MONTH_DAY));
                  DateTime endDay = DateTime.fromMillisecondsSinceEpoch(startDay.millisecondsSinceEpoch
                      + 14*24*3600*1000);
                  MediaPlayTimePage.navigatorPush(context, startDay: startDay, endDay: endDay, setTimeFlag:widget?.setTimeFlag??false, hsns: _getHsns(data),picid: widget?.picid??"");
                }else{
                  _viewModel.addMediaToTerminals(context, (_getSelectedCount(data) == data?.length)?"01":"00",
                      widget?.startday, widget?.endday, _getHsns(data), widget?.picid);
                }
            },
          ),
        ],
      ),
    );
  }

  String _getHsns(List<NewTerminalListItemBean> data){
    String hsns = "";
    data.forEach((element) {
      if(element.selectStatus){
        hsns += element.hsn;
        hsns += ",";
      }
    });

    if(StringUtils.isNotEmpty(widget?.cantManageHsns??"")){
        //不是超管
        if(!VgRoleUtils.isSuperAdmin(UserRepository.getInstance().getCurrentRoleId())){
          if(hsns.endsWith(",")){
            hsns += widget.cantManageHsns;
          }else{
            hsns += ",";
            hsns += widget.cantManageHsns;
          }
          hsns += ",";
        }
    }

    if(StringUtils.isNotEmpty(hsns)){
      hsns = hsns.substring(0, hsns.length-1);
    }
    return hsns;
  }



}